<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../css/login.css">
</head>
<body>
    <div class="photo">
        <img src="https://pic.mdcdn.cn/h5/pic/201704/1402b48b1915.jpg@100Q.jpg" alt="">
    </div>
    <div class="login">
        <form>
            <span class="error">用户名密码错误</span>
            <label>
                用户 ：<input type="text" class="username">
            </label>
            <label>
                  密码 ：<input type="text" class="password">
            </label>
            <p>如果没有账号,<a href="./register.html">前往注册</a></p>
        <button>登录</button>
        </form>
    </div>
    <script src="../js/utils.js"></script>
    <script>
const form = document.querySelector('form')
const nameInp = document.querySelector('.username')
const wordInp = document.querySelector('.password')
const error = document.querySelector('.error')
// 绑定事件 拿到Value
form.addEventListener('submit',e =>{
    e = e ||window.event
    try{ e.preventDefault()}catch(err){e.returnValue = false}
    const name = nameInp.value
    const password = wordInp.value
//  非空验证 
    if(!name || !password) window.alert('请完整填写表单')
//  发送请求
    const xhr = new XMLHttpRequest()
    xhr.open('POST','http://localhost:8081/xte/server/login.php')
    xhr.onload = () =>{
        const res = JSON.parse(xhr.responseText)
        if(res.code === 0){
            error.classList.add('active')
            return
        }
        // 表示登录过
        window.localStorage.setItem('login',1)
        // 存储凭证
        window.localStorage.setItem('token',res.token)
        // 存储 ID
        window.localStorage.setItem('id',res.id)
        //判断地址
        const url = window.localStorage.getItem('url')
        window.localStorage.removeItem('url')
        window.location.href = `${url ? url : 'index'}.html`
    }
    xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
    xhr.send(`username=${ name }&password=${ password }`)
})
    </script>
</body>
</html>